home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: artemis.sto.fdata.se!news
- From: Niklas Mellin <niklas.mellin@sto.fdata.se>
- Subject: Re: Calling the wrong constructor
- Sender: news@artemis.sto.fdata.se (UseNet NetNews)
- Message-ID: <3170DEB7.66C6@sto.fdata.se>
- Date: Sun, 14 Apr 1996 11:17:11 GMT
- Content-Transfer-Encoding: 7bit
- Content-Type: text/plain; charset=us-ascii
- References: <4kot87$796@earth.njcc.com> <4kpm4c$jfe@nntp1.best.com>
- Mime-Version: 1.0
- X-Mailer: Mozilla 2.0 (WinNT; I)
- Organization: WM-data F÷rsvarsdata AB, Sweden
-
- John Lockwood wrote:
- >
- > mike@pluto.njcc.com (Michael Hohenshilt) wrote:
- >
- > > This might seem like a basic question, but lets say you something set u
- > >like the following:
- >
- > >class Parent { Parent() { allocsomething} ~Parent() { deletesomething }... };
- > >class Foo : Parent { Foo() { allocsomething } ~Foo() {deletesomething }... };
- > >class Contain { Parent *ptr; ... };
- >
- > >both parent, and foo allocate memory, and will free it up when being
- > >destructed. Contain just holds a pointer of type Parent, and its
- > >constructor takes such a pointer as a parameter.
- > > If I store a pointer of type Foo into contain.ptr and discard that
- > >pointer. Is there any way to have contain (via destructors) free up all
- > >memory allocated by Foo and/or Parent?
- > > Mike
- >
- > The destructors need to be virtual.
- >
- > virtual ~Foo() { { /* ... */ }
- > virtual ~Parent() { /* ... */ }
-
- Only Parent has to be expicitly declared virtual, declaring derived
- classes overloaded functions as virtual when they are already declared
- virtual in the base class is optional. A good habit though since it
- might make the code clearer.
-
- > Then a base class pointer pointing to a derived class will do the
- > right thing. Note that the code as you've written it wouldn't
- > do any base class allocation, since you didn't call your parent
- > constructor.
-
- WRONG WRONG WRONG!!!!
-
- When the constructor of a derived class is called it will always
- first call the base class constructor. If nothing else is specified
- it will use the default constructor, and if there is no default
- constructor declared, the compiler will generate one for you.
-
- > Bad programmer! Just for that, no JOLT cola! ;-)
-
- Neither for you! ;-)
-
- ---
- Niklas Mellin
-